package com.topdt.jbpm.web.struts.action;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.thx.common.struts2.CurdAction;
import com.thx.common.util.AppContext;
import com.thx.common.web.ActionResult;
import com.thx.log.LogUtil;
import com.topdt.jbpm.form.SysParamService;
import com.topdt.jbpm.form.query.FieldType;
import com.topdt.jbpm.form.query.Param;
import com.topdt.jbpm.model.Application;
import com.topdt.jbpm.model.Control;
import com.topdt.jbpm.model.Field;
import com.topdt.jbpm.service.ApplicationService;
import com.topdt.jbpm.service.ControlService;
import com.topdt.jbpm.service.FieldService;
import com.topdt.jbpm.utils.ModuleConstant;
import com.topdt.jbpm.utils.SelectConstant;

@Namespace("/workflow")
@Action(value = "field",
		results = {
		@Result(name = "list",location = "/workflow/field/list.jsp"),
		@Result(name = "input",location = "/workflow/field/input.jsp"),
		@Result(name = "json", type = "json", params = { "root", "result" }),
		@Result(name = "selectJson", type = "json", params = { "root", "selectJson" })
		}
)
@Controller
@Scope("prototype")
/**
 * 
* @author _zili
* @ClassName: FieldAction 
* @Description:字段管理action
* @date 2015年4月1日 下午5:55:45
 */
public class FieldAction extends CurdAction<Field> {
	
	private static final long serialVersionUID = 1L;
	@Autowired
	FieldService fieldService;
	@Autowired
	ApplicationService appService;
	@Autowired
	private ControlService controlService;
	@Autowired
	private SysParamService  sysParamService;
	
	private String selectJson;
	private String appId;
	private List<FieldType> fieldTypeList;
	private List<Param> paramList;

	@Override
	protected void doList() throws Exception {
		logger.debug("<进入>:doList方法    字段列表");
		list = fieldService.getFieldsByformId(getFId());
	}
	
	@Override
	protected void doInput() throws Exception {
		logger.debug("<进入>:doInput方法");
		if (StringUtils.isNotBlank(id)) {
			entity = fieldService.get(id);
			if (entity == null) {
				setResult(ActionResult.FAIL, "要修改的记录不存在！！！");
			}
		}
		fieldTypeList = SelectConstant.listFieldType();
	}

	@Override
	protected void doSave() throws Exception {
		logger.debug("<进入>:doSave方法    添加或修改字段");
		try {
			String comId = AppContext.getCurrentComId();
			if (StringUtils.isBlank(id)) {
				entity.setFormId(getFId());
				entity.setCompanyId(comId);
				fieldService.save(entity);
				
				Application app = appService.get(appId);
				Object[] objs = new Object[]{appId,app.getFlowId(),getFId()};
	            List<Control> listControl = controlService.findControlByObjects(objs);
	            if(listControl!=null){
	                for(int i = 0; i<listControl.size();i++){
	                    Control control = listControl.get(i);
	                    control.setFieldControl(null);
	                    controlService.saveOrUpdate(control);
	                }
	                setResult(ActionResult.SUCCESS, "添加成功！，需要再次执行字段读写操作");
	            }else
	              setResult(ActionResult.SUCCESS, "添加成功！");
			} else {
				Field field = fieldService.get(id);
				boolean ischange = !field.getSeqenceNum().equals(entity.getSeqenceNum());
				
				field.setFieldName(entity.getFieldName());
				field.setDefaultValue(entity.getDefaultValue());
				field.setFieldLength(entity.getFieldLength());
				field.setFieldOption(entity.getFieldOption());
				field.setFieldText(entity.getFieldText());
				field.setFieldType(entity.getFieldType());
				field.setIsNecessary(entity.getIsNecessary());
				field.setIsShow(entity.getIsShow());
				field.setSeqenceNum(entity.getSeqenceNum());
				fieldService.save(field);
				
				Application app = appService.get(appId);
                Object[] objs = new Object[]{appId,app.getFlowId(),getFId()};
                List<Control> listControl = controlService.findControlByObjects(objs);
                //修改后 如果字段顺序发生变化，需要重置字段读写性
				if(listControl!=null&&ischange){
                  for(int i = 0; i<listControl.size();i++){
                      Control control = listControl.get(i);
                      control.setFieldControl(null);
                      controlService.saveOrUpdate(control);
                  }
                  setResult(ActionResult.SUCCESS, "修改成功！，需要再次执行字段读写操作");
                }else
                  setResult(ActionResult.SUCCESS, "修改成功！");
			}
			LogUtil.log(ModuleConstant.FIELD_MANAGE, StringUtils.isBlank(id)?LogUtil.ACTION_ADD:LogUtil.ACTION_UPDATE, LogUtil.RESULT_SUCCESS, "保存字段");
		} catch (Exception e) {
			if (StringUtils.isBlank(id)) {
				setResult(ActionResult.FAIL, "添加失败！");
			} else {
				setResult(ActionResult.FAIL, "修改失败！");
			}
			logger.error("<错误>:添加字段失败",e);
		}
	}

	@Override
	protected void doDelete() throws Exception {
		logger.debug("<进入>:doDelete方法    删除字段");
		if (StringUtils.isNotBlank(id)) {
			Application app = appService.get(appId);
			Object[] objs = new Object[]{appId,app.getFlowId(),getFId()};
			List<Control> listControl = controlService.findControlByObjects(objs);
			if(listControl!=null){
				for(int i = 0; i<listControl.size();i++){
					Control control = listControl.get(i);
					control.setFieldControl("");
					controlService.saveOrUpdate(control);
				}
				fieldService.delete(id);
				setResult(ActionResult.SUCCESS, "删除成功，需要再次执行字段读写操作");
			}else{
				fieldService.delete(id);
				setResult(ActionResult.SUCCESS, "删除成功！");
			}
			LogUtil.log(ModuleConstant.FIELD_MANAGE, LogUtil.ACTION_DELETE, LogUtil.RESULT_SUCCESS, "删除字段");
		} else {
			setResult(ActionResult.FAIL, "服务器异常！");
		}
	
	}
	public String findParam(){
		logger.debug("<进入>:findParam方法 参数："+entity.getFieldType());
		List<Param> paramList = null;
		try {
			if("more".equals(entity.getFieldType())){
				paramList = sysParamService.getAllFlatParam(entity.getFieldType());
			}
			if("single".equals(entity.getFieldType())){
				paramList = sysParamService.getAllFlatParam(entity.getFieldType());
			}
			if("tree".equals(entity.getFieldType())){
				paramList = SelectConstant.getTreeSelect();
			}
			if("system".equals(entity.getFieldType())){
				paramList = SelectConstant.getSystemSelect();
			}
			selectJson = com.alibaba.fastjson.JSON.toJSONString(paramList);
		} catch (Exception e) {
		    e.printStackTrace();
			logger.error("<错误>:查询参数名称失败",e);
		}
		return "selectJson";
	}
	/**
	 * 
	* @Description:验证字段名称代码的唯一性
	 */
	public void checkFieldName(){
		logger.debug("<进入>:checkFieldName方法   验证字段名称代码的唯一性");
		try {
			Field field = fieldService.findByFieldName(entity.getFieldName(), getFId());
			if (field != null) {
			    if(StringUtils.isNotBlank(id)){
			      Field f = fieldService.get(id);
                  if(entity.getFieldName().equals(f.getFieldName())){
                    writeJson("true");
                  }else{
                    writeJson("false");
                  }
			    }else{
			      writeJson("false");
			    }
			}else{
				writeJson("true");
			}
		} catch (Exception e) {
			logger.error("<错误>:验证字段名称代码的唯一性失败",e);
			setResult(ActionResult.FAIL, "服务器异常！");
		}
	}
	/**
	 * 
	* @Description:验证字段名称的唯一性
	 */
	public void checkFieldText(){
		logger.debug("<进入>:checkFieldText方法   验证字段名称的唯一性");
		try {
			Field field = fieldService.findByFieldText(entity.getFieldText(), getFId());
			if (field != null) {
			    if(StringUtils.isNotBlank(id)){
			      Field f = fieldService.get(id);
			      if(entity.getFieldText().equals(f.getFieldText())){
			        writeJson("true");
			      }else{
			        writeJson("false");
			      }
			    }else{
			      writeJson("false");
			    }
			}else{
				writeJson("true");
			}
		} catch (Exception e) {
			setResult(ActionResult.FAIL, "服务器异常！");
			logger.error("<错误>:验证字段名称的唯一性失败",e);
		}
	}
    public String getFId(){
    	logger.debug("<进入>:getFId方法");
    	Application app = appService.get(appId);
		String formId = null;
		if(app!=null){
			if(app.getForm()!=null){
				formId = app.getForm().getFormId();
			}
		}
		return formId;
    }
    
	public String getAppId() {
		return appId;
	}

	public void setAppId(String appId) {
		this.appId = appId;
	}

	public List<FieldType> getFieldTypeList() {
		return fieldTypeList;
	}

	public void setFieldTypeList(List<FieldType> fieldTypeList) {
		this.fieldTypeList = fieldTypeList;
	}

	public List<Param> getParamList() {
		return paramList;
	}

	public void setParamList(List<Param> paramList) {
		this.paramList = paramList;
	}

	public String getSelectJson() {
		return selectJson;
	}

	public void setSelectJson(String selectJson) {
		this.selectJson = selectJson;
	}
	
}
